/**
 * 登录模块 使用 json 文件来保存账号信息
 */
import * as fs from 'fs'
import * as path from 'path'
import { md5s, Exception, Succeed } from './index'
import Jwt from '../utils/token'
import * as Mock from 'mockjs'

/** 登录函数 */
export const post_login = async (req: any, res: any) => {
	const { username, password } = req.body
	let tip: any
	try {
		const data: any = await get_data()
		if (data == 'err')
			tip = new Exception(400, '还没有注册账号 , 请先注册账号').toObject()
		else {
			const { user } = data
			// 这个 if 可以不写 , 前端如果连这都不做判断就发请求...
			if (username && password) {
				// 注意 => 不要在循环里写逻辑
				// 先检查账号是否存在
				const urne: boolean = user.some((v: any) => v.username == username)
				let id: string = ''
				if (urne) {
					user.forEach((v: any) => {
						if (v.username == username && v.password == password) {
							id = v.id.toString()
						}
					})
				}
				if (!id) {
					tip = new Exception(400, '账号或密码错误').toObject()
				} else {
					// 这里进行加密处理 , 就算拿到 token 也无法反推账号是啥
					const name = md5s(username).substring(10)
					console.log('name >', name)
					const token = new Jwt(name).set_token()
					tip = Succeed({ token, id }, '登录成功')
				}
			} else {
				tip = new Exception(400, '没有输入账号密码').toObject()
			}
		}
	} catch (error) {
		tip = new Exception(400, error).toObject()
	}
	res.json(tip)
}

/** 注册函数 */
export const post_register = async (req: any, res: any) => {
	const { username } = req.body
	const new_user = users(req.body)
	console.log('new_user', new_user)
	let tip: any
	try {
		const data: any = await get_data()
		console.log('data', data)
		if (data == 'err') {
			// 拿不到文件 , 说明没有 index.json 文件
			// 第一次用 , 当然没有 index.json 文件
			const arr: any = { user: [] }
			arr.user.push(new_user)
			const back = await set_data(arr)
			if (back == 'err') {
				tip = new Exception(400, '注册失败').toObject()
			} else {
				tip = Succeed({}, '注册成功')
			}
		} else {
			const urne: boolean = data.user.some((v: any) => v.username == username)
			console.log('urne', urne)
			if (urne) {
				tip = new Exception(400, '注册失败 , 账号已经被注册').toObject()
			} else {
				data.user.push(new_user)
				const back = await set_data(data)
				if (back == 'err') {
					tip = new Exception(400, '注册失败').toObject()
				} else {
					tip = Succeed({}, '注册成功')
				}
			}
		}
	} catch (error) {
		tip = new Exception(400, error).toObject()
	}
	res.json(tip)
}

/** 读取文件 */
export const get_data = async () => {
	return new Promise(res => {
		fs.readFile(path.join(__dirname, '../../data/index.json'), (err, data) => {
			if (err) {
				return res('err')
			} else {
				const arr = JSON.parse(data.toString())
				return res(arr)
			}
		})
	}).catch(() => {
		return 'err'
	})
}

/**
 * 数据写入文件
 * @param db 需要写入的数据
 */
export const set_data = async (arr: any) => {
	const db = JSON.stringify(arr)
	return new Promise(res => {
		fs.writeFile(path.join(__dirname, '../../data/index.json'), db, err => {
			if (err) res('err')
			else res(null)
		})
	}).catch(() => {
		return 'err'
	})
}

/**
 * 注册添加默认信息
 * @param data 注册信息
 * @return 信息对象
 */
const users = (data: any) => {
	const { username, password, nickname = Mock.mock('@name') } = data
	return {
		id: Date.now().toString(),
		username,
		password,
		nickname,
		age: Mock.mock('@integer(18,30)'),
		gender: Mock.mock('@integer(0,1)'),
		user_date: new Date(),
		img: `https://img.yzcdn.cn/vant/apple-${Mock.mock('@integer(1,8)')}.jpg`
	}
}
